/*
 * Copyright 2016-2017 TVI Go Easy.
 * Created on 2017/4/29 15:34
 */
package org.mechanic.fund.service.product.impl;

import com.alibaba.fastjson.JSONObject;
import org.mechanic.core.Constants;
import org.mechanic.fund.domain.system.manager.Department;
import org.mechanic.fund.repository.system.DepartmentRepository;
import org.mechanic.fund.service.product.IDepartmentService;
import org.mechanic.fund.service.wechat.IWcAccessApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 部门信息服务实现
 *
 * @author mechanic
 * @version 0.0.1
 */
@Service
public class DepartmentService implements IDepartmentService {
    private final DepartmentRepository departmentRepository;
    private final IWcAccessApiService apiService;

    @Autowired
    public DepartmentService(DepartmentRepository departmentRepository, IWcAccessApiService apiService) {
        this.departmentRepository = departmentRepository;
        this.apiService = apiService;
    }

    /**
     * 返回匹配部门编号的部门信息
     *
     * @param id 部门编号
     * @return 部门信息
     */
    @Override
    @Cacheable(value = Constants.EHCACHE_NAME)
    public Department findById(String id) {
        return this.departmentRepository.findOne(id);
    }

    /**
     * 返回部门信息分页列表
     *
     * @param pageRequest  分页信息
     * @return 部门信息分页列表
     */
    @Override
    @Cacheable(value = Constants.EHCACHE_NAME)
    public Page<Department> getList(PageRequest pageRequest) {
        return this.departmentRepository.findAll(pageRequest);
    }

    /**
     * 删除匹配部门编号的部门信息
     *
     * @param id 部门编号
     */
    @Override
    public void delete(String id) {
        this.departmentRepository.delete(id);
    }

    /**
     * 保存部门信息
     *
     * @param departments     部门信息集合
     * @param operationUserId 操作该记录的部门主键编号
     */
    @Override
    @Transactional
    public Map save(List<Department> departments, String operationUserId) {

        //Department saved = this.departmentRepository.save(DtoBeanMapper.setOperationToDomain(departments.get(0), operationUserId));
        Department saved = this.departmentRepository.save(departments.get(0));
        Map<String, String> wcDepartment = new LinkedHashMap<>();
        wcDepartment.put("name", saved.getName());
        wcDepartment.put("parentid", saved.getWxParent().getId());
        wcDepartment.put("order", saved.getSort().toString());
        wcDepartment.put("id", saved.getId());
        return this.apiService.saveDepartment(JSONObject.toJSONString(wcDepartment));
    }
}
